//
//  UITextView+Extension.swift
//  weibo
//
//  Created by 邵帅 on 16/7/3.
//  Copyright © 2016年 groupNineObject. All rights reserved.
//

import UIKit


extension UITextView {
    
    // 插入表情
    func insertEmoticon(emoticon: SSEmoticon) {
        
        if let _ = emoticon.png {
            
            // 定义可变数组，拼接内容
            let mutAtrribute = NSMutableAttributedString(attributedString: attributedText)
            
            // 附件
            let attachment = SSTextAttachment()
            attachment.emoticon = emoticon
            
            let attribute = attachment.getAttibuteString(self.font!)
            
            // 拼接
            let range = self.selectedRange
            
            if let myAttribute = attribute {
                
                mutAtrribute.replaceCharactersInRange(range, withAttributedString: myAttribute)
                
            }
            
            // 修改属性
            mutAtrribute.addAttributes([NSFontAttributeName: self.font!], range: NSMakeRange(0, mutAtrribute.length))
            
            // 赋值
            attributedText = mutAtrribute
            
            // 让光标回到原来位置
            self.selectedRange = NSMakeRange(range.location + 1, 0)
            
            // 调用代理，让占位文字消失
            self.delegate?.textViewDidChange!(self)
        }
        
        // emoji
        if let emoji = emoticon.emoji {
            
            self.replaceRange(self.selectedTextRange!, withText: emoji)
        }
        
    }
    
    
    // 拼接字符串
    func setPublishTextString() -> String? {
        
        var publishString = String()
        
        self.attributedText.enumerateAttributesInRange(NSMakeRange(0, self.attributedText.length), options: []) { (data, range, _) in
            
            if let attachment = data["NSAttachment"] as? SSTextAttachment{
            
                if let chs = attachment.emoticon?.chs {
                
                    publishString = publishString + chs
                    
                }
            
                
            } else {
                
                let subString = (self.text as NSString).substringWithRange(range)
                    
                publishString = publishString + subString
                
                
            }
            
        }
        
        return publishString
    }
    
    
}